/*************************************************************************
 * File Name:    Word_Search.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/7 1:13:10
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Word Search
 |
 | Given a 2D board and a word, find if the word exists in the grid.
 |
 | The word can be constructed from letters of sequentially adjacent cell,
 | where "adjacent" cells are those horizontally or vertically neighboring.
 | The same letter cell may not be used more than once.
 |
 | For example,
 | Given board =
 |
 | [
 |   ["ABCE"],
 |   ["SFCS"],
 |   ["ADEE"]
 | ]
 |
 | word = "ABCCED", -> returns true,
 | word = "SEE", -> returns true,
 | word = "ABCB", -> returns false.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word)
    {
        if (board.size() == 0) return false;
        int row = board.size();
        int col = board[0].size();
        
        vector<vector<bool> > visited(row, vector<bool>(col, false));
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (board[i][j] == word[0] && dfs(board, visited, word, 1, i, j)) return true;
            }
        }
        return false;
    }

private:
    bool dfs(const vector<vector<char> > &board, vector<vector<bool> > &visited, const string &word, int p, int i, int j)
    {
        if (word.size() == p) return true;
        const int move[4][2] = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
        
        int row = board.size();
        int col = board[0].size();
        
        visited[i][j] = true;
        for (int k = 0; k < 4; ++k) {
            int x = i + move[k][0];
            int y = j + move[k][1];
            
            if (x >= 0 && x < row && y >= 0 && y < col && !visited[x][y] && word[p] == board[x][y]) {
                if (dfs(board, visited, word, p + 1, x, y)) return true;
            }
        }
        visited[i][j] = false;
        return false;
    }
};

int
main(int argc, char *argv[])
{
    Solution sol;

    vector<vector<char> > board;
    string word = "aa";

    board.push_back(vector<char>(2, 'a'));

    cout << sol.exist(board, word) << endl;

    return 0;
}
